<?php
require_once(APPPATH.'views/components/page.php');
require_once(APPPATH.'libraries/branchobject.php');

/**
 * Branch controller
 */
class Branch extends CI_Controller
{
	
	function __construct()
	{
		parent::__construct();
		
		$this->load->model('branch_model');
	}
	
	public function index()
	{
		if (Page::getInstance()->isAdmin())
		{
			$data['branches'] = $this->branch_model->getAllBranches();
			$this->load->view("branches/branch_admin_view", $data);
		}
		else
		{
			redirect(site_url());
		}
	}
	
	public function insert()
	{
		if (Page::getInstance()->isAdmin())
		{
			$error = ERROR_NONE;
			$name = $this->input->post('branchname');
			
			if ($this->branch_model->findBranch($name) < 0)
			{
				$branch = new BranchObject(-1, $name);
				$error = $this->branch_model->insertBranch($branch);
			}
			else
			{
				$error = EXISTED_ERROR;
				$this->session->set_userdata('branchname', $name);
			}
			
			$this->session->set_userdata('error', $error);
			redirect('branch');
		}
		else
		{
			redirect(site_url());
		}
	}
	
	public function delete()
	{
		if (Page::getInstance()->isAdmin())
		{
			$error = ERROR_NONE;
			$ids = $this->input->post('branches');
			
			$error = $this->branch_model->deleteMultipleBranches($ids);
			
			$this->session->set_userdata('error', $error);
			redirect('branch');
		}
		else
		{
			redirect(site_url());
		}
	}
	
	public function view($id)
	{
		if (Page::getInstance()->isAdmin())
		{
			$branch = $this->branch_model->getBranchById($id);
			
			if ($branch->getId() <= 0)
				$data['rerror'] = NOT_EXISTED_ERROR;
			
			$data['branch'] = $branch;
			$this->load->view('branches/branch_admin_detail', $data);
		}
		else
		{
			redirect(site_url());
		}
	}
	
	public function update()
	{
		if (Page::getInstance()->isAdmin())
		{
			$error = ERROR_NONE;
			$name = $this->input->post('branchname');
			$id = $this->input->post('branchid');
			$branch = $this->branch_model->getBranchById($id);
			
			$foundId = $this->branch_model->findBranch($name);
			$existed = FALSE;
			
			if ($foundId == $id)
				$existed = FALSE;
			else {
				if ($foundId > 0)
					$existed = TRUE;
			}
		
			if (! $existed)
			{
				$branch->setName($name);
				$error = $this->branch_model->updateBranch($id, $branch);
			}
			else
			{
				$error = EXISTED_ERROR;
				$this->session->set_userdata('branchname', $name);
			}
			
			$this->session->set_userdata('error', $error);
			
			if ($error == ERROR_NONE)
			{
				redirect('branch');
			}
			else {
				redirect('branch/view/'.$id);
			}
		}
		else
		{
			redirect(site_url());
		}
	}
}
/* End of file branch.php */
/* Location: ./application/controllers/branch.php */